package org.insia.smartposse.dao;

import org.insia.smartposse.config.DAOFactory;
import org.insia.smartposse.idao.ICompanyDAO;
import org.insia.smartposse.metier.Company;
import org.insia.smartposse.metier.webservice.LightCompany;
import org.insia.smartposse.utils.PasswordEncoder;

/**
 * DAO for Company class based on GenericDAO.
 * @author sok hout
 *
 */
public class CompanyDAO 
extends GenericDAO<Company, Long>
implements ICompanyDAO {

	/**
	 * Empty constructor.
	 *
	 */
	public CompanyDAO() {
		type = Company.class;
	}

	/* (non-Javadoc)
	 * @see org.insia.smartposse.idao.ICompanyDAO#createLightCompany(org.insia.smartposse.metier.webservice.LightCompany)
	 */
	public LightCompany createLightCompany(LightCompany lcompany) {
		try {
			Company company = new Company();
			company.setAddress(lcompany.getAddress());
			company.setEmail(lcompany.getEmail());
			company.setFirstName(lcompany.getFirstName());
			company.setGender(lcompany.getGender());
			company.setLastName(lcompany.getLastName());
			company.setLogin(lcompany.getLogin());
			company.setUrl(lcompany.getUrl());
			company.setName(lcompany.getName());
			company.setPassword(PasswordEncoder.encode(lcompany.getPassword()));
			lcompany.setId(DAOFactory.getCompanyDAO().create(company));
			
			if (lcompany.getProjectSet().size() != 0) {
				lcompany.setProjectSet(DAOFactory.getProjectDAO().createLightProject(lcompany.getProjectSet()));
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return lcompany;
	}

	/*
	 * (non-Javadoc)
	 * @see org.insia.smartposse.idao.ICompanyDAO#updateLightCompany(org.insia.smartposse.metier.webservice.LightCompany)
	 */
	public LightCompany updateLightCompany(LightCompany lcompany) {
		try {
			Company company = DAOFactory.getCompanyDAO().get(lcompany.getId());
			company.setAddress(lcompany.getAddress());
			company.setEmail(lcompany.getEmail());
			company.setFirstName(lcompany.getFirstName());
			company.setGender(lcompany.getGender());
			company.setLastName(lcompany.getLastName());
			company.setLogin(lcompany.getLogin());
			company.setUrl(lcompany.getUrl());
			company.setName(lcompany.getName());
			company.setPassword(PasswordEncoder.encode(lcompany.getPassword()));
			
			
			if (lcompany.getProjectSet().size() != 0) {
				lcompany.setProjectSet(DAOFactory.getProjectDAO().updateLightProject(lcompany.getProjectSet()));
			}
			DAOFactory.getCompanyDAO().update(company);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
		return lcompany;
	}
}
